package com.treetao.union.web.shiro;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.treetao.union.core.util.SpringContextHolder;
import com.treetao.union.db.model.SysUser;
import com.treetao.union.db.service.SysSiteService;
import com.treetao.union.db.service.SysUserService;
import com.treetao.union.web.constant.Constants;

@Component
public class MyHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    private SysUserService userService;
    
    @Autowired
    private SysSiteService sysSiteService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {
        if ( userService == null) {//解决service为null无法注入问题
            userService = (SysUserService) SpringContextHolder.getBean("userService");
        }
        if ( sysSiteService == null) {//解决service为null无法注入问题
        	sysSiteService = (SysSiteService) SpringContextHolder.getBean("siteService");
        }
        Long id = MySysUser.id();
        httpServletRequest.setAttribute("site", sysSiteService.getCurrentSite());
        if(id!=null) {
        	httpServletRequest.setAttribute("adminPrefix",Constants.AMIND_PREFIX);
        	SysUser user = userService.findUserById(id);
	        if(user != null){
	            httpServletRequest.setAttribute("currentUser",user);
	            return true;
	        }
        } else {
        	try {
        		SecurityUtils.getSubject().logout();
				httpServletResponse.sendRedirect("");
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
